// 管理员首页内容组件（占满宽度版）
Vue.component('admin-home-content', {
  data() {
    return {
      employeeCount: 56,
      departmentCount: 7,
      attendanceRate: 98.2,
      performanceAvg: 87.5,
      // 图表数据
      departmentDistribution: [
        { name: '技术部', value: 18 },
        { name: '市场部', value: 10 },
        { name: '人力资源部', value: 6 },
        { name: '财务部', value: 5 },
        { name: '运营部', value: 9 },
        { name: '销售部', value: 8 }
      ],
      monthlyAttendance: {
        months: ['1月', '2月', '3月', '4月', '5月', '6月'],
        rates: [97.5, 96.8, 98.1, 97.9, 98.5, 98.2]
      }
    };
  },
  mounted() {
    // 加载数据
    this.loadData();
    // 等待DOM渲染完成后初始化图表
    this.$nextTick(() => {
      this.initDepartmentChart();
      this.initAttendanceChart();
      // 监听窗口大小变化，调整图表尺寸
      window.addEventListener('resize', this.handleResize);
    });
  },
  beforeDestroy() {
    // 清理事件监听
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    // 加载管理员首页数据
    async loadData() {
      try {
        const response = await statisticsAPI.getDashboardData();
        const data = response.data;
        
        // 设置统计数据
        this.employeeCount = data.employee_count;
        this.departmentCount = data.department_count;
        this.attendanceRate = data.attendance_rate;
        this.performanceAvg = data.performance_avg;
        
        // 设置图表数据
        this.departmentDistribution = data.department_distribution;
        this.monthlyAttendance = data.monthly_attendance;
        
        // 重新初始化图表
        this.$nextTick(() => {
          this.initDepartmentChart();
          this.initAttendanceChart();
        });
        
      } catch (error) {
        console.error('加载管理员首页数据失败:', error);
        this.$message.error('数据加载失败，使用模拟数据');
      }
    },

    // 初始化部门分布饼图
    initDepartmentChart() {
      if (!window.echarts) {
        console.error('ECharts library is not loaded');
        return;
      }
      
      const chartDom = document.getElementById('departmentChart');
      if (!chartDom) return;
      
      const myChart = window.echarts.init(chartDom);
      
      const option = {
        title: {
          text: '部门员工分布',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          bottom: 10,
          // 响应式调整图例
          formatter: function(name) {
            return name.length > 6 ? name.substring(0, 6) + '...' : name;
          }
        },
        series: [
          {
            name: '员工数量',
            type: 'pie',
            radius: '60%',
            center: ['50%', '45%'],
            data: this.departmentDistribution,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              formatter: '{b}: {d}%'
            }
          }
        ]
      };
      
      myChart.setOption(option);
      // 保存图表实例以便调整大小
      this.departmentChartInstance = myChart;
    },
    
    // 初始化出勤率趋势柱状图
    initAttendanceChart() {
      if (!window.echarts) {
        console.error('ECharts library is not loaded');
        return;
      }
      
      const chartDom = document.getElementById('attendanceChart');
      if (!chartDom) return;
      
      const myChart = window.echarts.init(chartDom);
      
      const option = {
        title: {
          text: '近6个月出勤率趋势',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: '{b}: {c}%'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.monthlyAttendance.months
        },
        yAxis: {
          type: 'value',
          min: 95,
          max: 100,
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: [
          {
            name: '出勤率',
            type: 'bar',
            data: this.monthlyAttendance.rates,
            itemStyle: {
              color: new window.echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            },
            label: {
              show: true,
              position: 'top',
              formatter: '{c}%'
            }
          }
        ]
      };
      
      myChart.setOption(option);
      // 保存图表实例以便调整大小
      this.attendanceChartInstance = myChart;
    },
    
    // 处理窗口大小变化
    handleResize() {
      if (this.departmentChartInstance) {
        this.departmentChartInstance.resize();
      }
      if (this.attendanceChartInstance) {
        this.attendanceChartInstance.resize();
      }
    }
  },
  template: `
    <div style="padding: 20px; width: 100%; box-sizing: border-box;">
      <el-card shadow="hover" style="width: 100%;">
        <div style="font-size: 22px; font-weight: bold; margin-bottom: 18px;">管理员首页数据概览</div>
        <el-row :gutter="20" style="margin-bottom: 20px;">
          <!-- 使用响应式栅格，在小屏幕上自动堆叠 -->
          <el-col :xs="12" :sm="6" :lg="6">
            <el-statistic title="员工总数" :value="employeeCount" suffix="人"></el-statistic>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="6">
            <el-statistic title="部门数量" :value="departmentCount" suffix="个"></el-statistic>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="6">
            <el-statistic title="本月出勤率" :value="attendanceRate" suffix="%"></el-statistic>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="6">
            <el-statistic title="绩效平均分" :value="performanceAvg" suffix="分"></el-statistic>
          </el-col>
        </el-row>
      </el-card>
      
      <!-- 图表区域 - 占满宽度并响应式调整 -->
      <el-row :gutter="30" style="margin-top: 20px; width: 100%;">
        <!-- 部门分布饼图 - 在小屏幕上占满整行 -->
        <el-col :xs="24" :lg="12">
          <el-card shadow="hover" style="width: 100%; height: 100%;">
            <div id="departmentChart" style="width: 100%; height: 400px;"></div>
          </el-card>
        </el-col>
        <!-- 出勤率趋势柱状图 - 在小屏幕上占满整行 -->
        <el-col :xs="24" :lg="12">
          <el-card shadow="hover" style="width: 100%; height: 100%;">
            <div id="attendanceChart" style="width: 100%; height: 400px;"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  `
});